<?php 

class Storage_File  
{
  /**
   * Path were we have to save content
   * 
   * @var string
   */
  protected $path;
  /**
   * Content objct
   * 
   * @var DOMDocument
   */
  protected $content;
  /**
   * Method to get content structure
   */
  private function getContent()
  {
    return $this->content;
  }
  
  /**
   * Class constructor
   * 
   * @param Array $options
   */
  public function __construct($options)
  {
    if(!isset($options["path"]))
    {
      throw new Exception("Folder have not been defined!");
    }
    
    $this->path = $options["path"];
  }
  /**
   * Method to set content   
   * 
   * @param DOMDocument $content
   */  
  public function content(DOMDocument $content)
  {
    $this->content = $content;
    
    return $this;
  }
  /**
   * Method to normalize string 
   * 
   * @param string $string
   */
  public function normalize($string)
  {
    return mb_substr(preg_replace("/[^\w\d]/u", "", $string), 0, 64);
  }
  /**
   * Method to save accepted content
   * 
   * @param unknown_type $encoding
   */
  public function save($from_encoding = NULL, $to_encoding = NULL)
  {
    $name = $this->normalize($this->getContent()->getTitle());
    $html = $this->getContent()->saveHTML();

    // Если не удалось получить кодировку из хидеров, получаем из контента
    if(is_null($from_encoding))
    {
      $from_encoding = $this->getContent()->getEncoding(); 
    }
    
    // Если заданы начальная и конечная кодировки  конвертаем текст в нужный формат
    if(!is_null($from_encoding) && !is_null($to_encoding))
    {
      iconv_set_encoding("input_encoding",    $to_encoding);
      iconv_set_encoding("output_encoding",   $to_encoding);
      iconv_set_encoding("internal_encoding", $to_encoding);
      
      $html = iconv($from_encoding, $to_encoding, $html);
    }
    
    $path = $this->path . "/" . $this->getContent()->getDomain($this->getContent()->getUrl());
    
    if (! file_exists($path))
    {
      mkdir($path);
    }
    
    $file = fopen($path . "/" . $name . ".txt", "w");
    
    if(is_resource($file))
    {
      fwrite($file, $html);
      fclose($file);
    }
    
    return $this;
  }
}